//
//  WeightListViewController.m
//  IWeighMyself
//
//  Created by Francisco Gindre on 8/24/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WeightListViewController.h"
#import "IWeighMyselfAppDelegate.h"
#import "DatabaseUtils.h"
#import "Weight.h"

#import "EditWeightEntryViewController.h"
@implementation WeightListViewController
@synthesize weightEntryCell;
@synthesize entries;
@synthesize appDelegate;
@synthesize initialDate;
@synthesize endingDate;


#pragma mark -
#pragma mark View lifecycle

-(id)initWithDateRange:(NSDate*)fromDate to:(NSDate*)endDate {
	
	
	
	self = [[WeightListViewController alloc]initWithNibName:@"WeightListViewController" bundle:[NSBundle mainBundle]];
	//NSLog(@"database path %@",dbPath);
	
	
	if (self !=nil) {
		
		
		self.appDelegate = [[[UIApplication sharedApplication]delegate] retain];
		
		NSString *dbPath = [[NSString stringWithString:appDelegate.databasePath] retain];
		
		[self loadEntriesFromDatabase:dbPath startingDate:fromDate EndDate:endDate];
		
		/*
		 if the dates received are not nil, retain them, otherwise just keep the nil
		 */
		
		if (fromDate) {
			self.initialDate = [fromDate retain];
		}else {
			self.initialDate = fromDate;
			
		}
		
		if (endDate) {
			self.endingDate = [endingDate retain];
		}else {
			self.endingDate = endingDate;
		}


		//release dbPath
		[dbPath release];
	}
	[self.entries retain];
	
	return self;
}


- (void)viewDidLoad {
	
    [super viewDidLoad];

	// allow selection during editing mode
	
	[self.tableView setAllowsSelectionDuringEditing:YES];
	// set title
	self.title = NSLocalizedString(@"WeightHistoryTitle",@"");
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	self.navigationItem.rightBarButtonItem = self.editButtonItem;
	[self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(@"EditButtonTitle",@"")];

	//	[self printEntries];
	
	[self.navigationItem.backBarButtonItem  setTitle: NSLocalizedString(@"BackButtonTitle",@"")];
	
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [entries count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!appDelegate){
		self.appDelegate =[[UIApplication sharedApplication ]delegate];
	}
    static NSString *CellIdentifier = @"WeightEntryCellIdentifier";
    
    WeightEntryCell *cell = (WeightEntryCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
	
	Weight *currentEntry = [self.entries objectAtIndex:indexPath.row] ;
	
	if (cell == nil) {
      //  cell = [[WeightEntryCell alloc] initWithWeight:currentEntry];
		[[NSBundle mainBundle] loadNibNamed:@"WeightTableViewCell" owner:self options:nil];
		cell = self.weightEntryCell;
		
		//self.weightEntryCell = nil;
		
	}
	
    // Configure the cell...
   
	//set the date from the weight in the entry.
	
	NSDate *aDate = [[currentEntry dateLogged] retain];
	
	NSString *stringDate = [NSDateFormatter localizedStringFromDate:aDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle]; 
	
	//NSLog(@"stringdate is %@", stringDate);
	[cell.dateLabel setText:stringDate];
	
	NSString *unit;
	
	/*
	 set the weight and unit for this weight
	 */
	
	
	if ([appDelegate isKilosWeightSelectedUnit]) {
		unit = NSLocalizedString(@"WeightUnitKilos",@"");
		
		NSString *weightString = [NSString stringWithFormat:@"%.1f ",[currentEntry.weightInKilos floatValue]];
		
		[cell.weightLabel setText:[weightString stringByAppendingString:unit]];
		
	} else {
		NSString *weightString = [NSString stringWithFormat:@"%.1f ",[currentEntry.weightInPounds floatValue]];
		unit = NSLocalizedString(@"WeightUnitPounds",@"");
		[cell.weightLabel setText:[weightString stringByAppendingString:unit]];
	}
	//release memory
	//[appDelegate release];
	//[unit release];
	//[currentEntry release];
	
	
	return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		
	//	NSLog(@"indexpath row: %d, indexpath section: %d",indexPath.row,indexPath.section);
		
		/**
		 get the weight to delete 
		 */
		Weight *weightToDelete = [[self.entries objectAtIndex:indexPath.row] retain];
		
	//	NSLog(@"weightToDelete %@",[weightToDelete weightToString]);
		
		/*
		 remove it from data source
		 */
		[entries removeObjectAtIndex:indexPath.row];
		
		/*
		 now from database
		 */
		[DatabaseUtils deleteWeightFromDatabase: appDelegate.databasePath  weightToDelete:weightToDelete fromTable:@"weight"];
		
		/*
		 release last retain count
		 */
		
		[weightToDelete release];
		
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		
	
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	if ([tableView isEditing]) {
		Weight *toEdit = [entries objectAtIndex:indexPath.row];
		
		
		//EditWeightEntryViewController *editController = ;
		[self.navigationController pushViewController:[[EditWeightEntryViewController alloc] initWithWeight:toEdit theWeightList:self] animated:YES];
		
		
		//NSLog(@"is in editing mode");
		
	
		
	}
	//NSLog(@"not in editing mode: skipping request");
}

#pragma mark -
#pragma mark refresh methods

-(void)loadEntriesFromDatabase:(NSString*)dbPath startingDate:(NSDate*)fromDate EndDate:(NSDate*)endDate {
	/*
	 if there are no date limits get everything
	 */
	
	if (fromDate ==nil && endDate ==nil){
		self.entries = [[DatabaseUtils queryAllEntriesFromDatabase:dbPath  fromTable:@"weight"] retain];
	}
	/*
	 if there is no end date, then get everything from that date on
	 */
	
	if (fromDate !=nil && endDate ==nil) {
		self.entries = [[DatabaseUtils queryAllEntriesFromDatabaseBetweenDates:dbPath fromTable:@"weight" from:fromDate to:[NSDate date]]retain];
		
		
	}
	
	if (fromDate ==nil && endDate != nil ) {
		self.entries = [[DatabaseUtils queryAllEntriesFromDatabaseBetweenDates:dbPath fromTable:@"weight" from:[NSDate dateWithTimeIntervalSince1970:0] to:endDate]retain];
		
	}
	if (fromDate !=nil && endDate !=nil) {
		self.entries = [[DatabaseUtils queryAllEntriesFromDatabaseBetweenDates:dbPath fromTable:@"weight" from:fromDate to:endDate]retain];
		
	}
	
	
}
/**
 ViewController gets notified the user changed the values by editing the entry. The entries need to be refreshed from database
 
 */
-(void)userEditedValue {
	
	[self.entries release];
	[self loadEntriesFromDatabase:appDelegate.databasePath startingDate:self.initialDate EndDate:self.endingDate];
	[self.tableView reloadData];
	
}
					

#pragma mark -
#pragma mark auxiliary methods
		 
-(void)printEntries {
	for (int i=0; i<[entries count]; i++) {
		NSLog(@"Entry %d: \n %@ \n =======",i,[[entries objectAtIndex:i]weightToString]);
	}
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[appDelegate release];
}


@end

